package org.raymond.iworks.gateway.filter;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.raymond.iworks.apis.common.ErrorCode;
import org.raymond.iworks.apis.exception.BaseException;
import org.raymond.iworks.commons.constants.CommonConstants;
import org.raymond.iworks.core.constants.SecurityComponets;
import org.raymond.iworks.gateway.filter.support.FilterOrder;
import org.raymond.iworks.gateway.filter.support.GatewayContext;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

@Slf4j
public class GatewayContextFilter implements GlobalFilter, Ordered {
    private RSA rsa = SecurityComponets.DEFAULT_ENCRYPTOR;

    private static String key = "abcdefghijklmnop";
    private static String iv = "0987654321012345";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI requestUri = request.getURI();
        String requestPath = requestUri.getPath();

        if (log.isDebugEnabled()) {
            log.debug("requestUri:{}", requestUri);
        }

        Object cachedBody = exchange.getAttribute(ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR);
        if (cachedBody != null) {
            return chain.filter(exchange);
        }

        GatewayContext gatewayContext = new GatewayContext();
        HttpHeaders headers = request.getHeaders();
        Long gatewayIn = System.currentTimeMillis();
        exchange.getAttributes().put("gatewayIn", gatewayIn);
        exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT, gatewayContext);

        AES aes = null;
        String decryptedSign = null;
        if (CommonConstants.ENCRYPT_ENABLE) {
            String encryptedKey = headers.getFirst(CommonConstants.SYMMETRY_HEADER_CRYPTO);
            String encryptedIv = headers.getFirst(CommonConstants.SYMMETRY_HEADER_IV);
            String encryptedSign = headers.getFirst(CommonConstants.SYMMETRY_HEADER_SIGN);
            if (StringUtils.isBlank(encryptedKey) || StringUtils.isBlank(encryptedIv) || StringUtils.isBlank(encryptedSign)) {
                log.error("Key, iv or sign is empty. key:{}, iv:{}, sign:{}", encryptedKey, encryptedIv, encryptedSign);
                throw new BaseException(ErrorCode.BAD_REQUEST);
            }
            String key = rsa.decryptStr(encryptedKey, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
            String iv = rsa.decryptStr(encryptedIv, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
            if(log.isDebugEnabled()) {
                log.debug("key:{}, iv:{}", key, iv);
            }
            aes = new AES("CBC", "PKCS7Padding", key.getBytes(StandardCharsets.UTF_8), iv.getBytes(StandardCharsets.UTF_8));
            decryptedSign = aes.decryptStr(encryptedSign);
            gatewayContext.setAes(aes);
            gatewayContext.setSign(decryptedSign);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterOrder.GatewayContextFilter;
    }
}
